/**
 * 将简单类型数据表导出成 xls
 */

/**
 * 由数据生成虚拟的 table
 * @param {Array} data
 *  [
 *   ['id', 'name', 'date'],  -> thead
 *   [1, 'jack', '2019/1/22'], -> tbody
 *   [2, 'rose', '2018/1/22'], -> tbody
 *  ]
 */
const generate_table_from_data = data => {
  if (!data[0] || !data[0][0]) return data

  const dataThead = data[0].shift()
  const dataTbody = data[0]

  const reducer = type => (accumulator, currentValue) => accumulator + `<${ type }>${ currentValue }</${ type }>`
  const textThead = dataThead.reduce(reducer('th'), '<tr>') + '</tr>'
  const textTbody = dataTbody.reduce(reducer('td'), '<tr>') + '</tr>'

  const nodeTable = document.createElement('table')
  nodeTable.cssText = 'position: fixed; z-index: -9999; display: none;'
  nodeTable.innerHTML = `<thead>${ textThead }</thead><tbody>${ textTbody }</tbody>`
  return nodeTable
}

const tableToExcel = (function() {
  const uri = 'data:application/vnd.ms-excel;base64,'
  const template = '<html><head><meta charset="UTF-8"></head><body><table><tr><td>{table}</td></tr></table></body></html>'
  const base64 = function(s) {
    return window.btoa(unescape(encodeURIComponent(s)))
  }
  const format = function(s, c) {
    return s.replace(/{(\w+)}/g,
      function(m, p) {
        return c[p]
      })
  }

  return function(table, name) {
    if (!table.nodeType) table = document.getElementById(table)
    var ctx = {
      worksheet: name || 'Worksheet',
      table: table.outerHTML
    }
    window.location.href = uri + base64(format(template, ctx))
  }
}())

export function export_json_to_excel(data, filename = 'excel') {
  const table = generate_table_from_data(data)

  if ('btoa' in window) {
    tableToExcel(table, filename)
  } else if ('ActiveXObject' in window) {
    let xObj = new ActiveXObject('Excel.Application') // eslint-disable-line
    let xExcel = null
    const wBook = xObj.Workbooks.Add()
    const wSheet = wBook.Worksheets(1)
    const tRange = document.body.createTextRange()
    tRange.moveToElementText(table)
    // tRange.select()
    tRange.execCommand('Copy')
    wSheet.Paste()
    xObj.Visible = true

    try {
      xExcel = xObj.Application.GetSaveAsFilename(filename + '.xls', 'Excel Spreadsheets (*.xls), *.xls')
    } catch (e) {
      //
    } finally {
      xExcel && wBook.SaveAs(xExcel)
      wBook.Close(false)
      xObj.Quit()
      xObj = null
    }
  } else {
    alert('您的浏览器过于老旧，不支持导出')
  }
}
